<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\adminapi\controller\user;

use app\adminapi\controller\Base;
use app\adminapi\validate\user\PointsValidate;
use app\common\model\UserPointsLog;
use app\common\model\User;
use think\facade\Db;

class Points extends Base
{
    /**
     * 获取积分记录列表
     */
    public function lists()
    {
        $user_id = $this->request->post('user_id', 0);
        $type    = $this->request->post('type', '');

        $where = [];
        if ($user_id) {
            $where[] = ['user_id', '=', $user_id];
        }
        if ($type) {
            $where[] = ['type', '=', $type];
        }

        $pointsModel = new UserPointsLog();

        $res = $pointsModel->where($where)
            ->with(['user'])
            ->order('id', 'desc')
            ->paginate($this->limit);

        return $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ]);
    }

    /**
     * 获取积分类型列表
     */
    public function types()
    {
        $types = [
            'register'       => '注册奖励',
            'sign'           => '签到奖励',
            'purchase'       => '购买商品',
            'comment'        => '评论奖励',
            'liked'          => '评论被点赞',
            'favorite'       => '内容被收藏',
            'profile'        => '完善资料',
            'bind_mobile'    => '绑定手机',
            'first_recharge' => '首次充值',
            'invite'         => '邀请注册',
            'exchange'       => '积分兑换',
            'consume'        => '积分消费',
            'admin_adjust'   => '管理员调整',
            'other'          => '其他'
        ];

        return $this->success('', $types);
    }

    /**
     * 手动调整用户积分
     */
    public function adjust()
    {
        $validate = new PointsValidate();
        $data     = $validate->data('adjust');

        // 检查用户是否存在
        $user = User::find($data['user_id']);
        if (!$user) {
            return $this->error(trans('member_not_exists'));
        }

        // 开始事务
        Db::startTrans();
        try {
            // 记录调整前的积分
            $beforePoints = $user->points;

            // 计算调整后的积分
            $afterPoints = $beforePoints + $data['points'];
            if ($afterPoints < 0) {
                return $this->error(trans('points_not_enough'));
            }

            // 创建积分记录
            $pointsLog                = new UserPointsLog();
            $pointsLog->user_id       = $data['user_id'];
            $pointsLog->points        = $data['points'];
            $pointsLog->before_points = $beforePoints;
            $pointsLog->after_points  = $afterPoints;
            $pointsLog->type          = 'admin_adjust';
            $pointsLog->remark        = $data['remark'] ?? '管理员调整积分';
            $pointsLog->save();

            // 更新用户积分
            $user->points = $afterPoints;
            $user->save();

            // 检查是否需要更新会员等级
            $user->checkAndUpdateLevel();

            Db::commit();
            return $this->success();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    /**
     * 获取用户积分统计
     */
    public function userStats()
    {
        $user_id = $this->request->post('user_id', 0);
        if (!$user_id) {
            return $this->error(trans('parameter_error'));
        }

        // 检查用户是否存在
        $user = User::find($user_id);
        if (!$user) {
            return $this->error(trans('member_not_exists'));
        }

        // 获取用户积分统计
        $stats = [
            'total_points'   => $user->points,
            'total_earned'   => UserPointsLog::where('user_id', $user_id)
                ->where('points', '>', 0)
                ->sum('points'),
            'total_consumed' => UserPointsLog::where('user_id', $user_id)
                ->where('points', '<', 0)
                ->sum('points'),
            'today_earned'   => UserPointsLog::where('user_id', $user_id)
                ->where('points', '>', 0)
                ->whereDay('create_time')
                ->sum('points'),
            'today_consumed' => UserPointsLog::where('user_id', $user_id)
                ->where('points', '<', 0)
                ->whereDay('create_time')
                ->sum('points'),
            'month_earned'   => UserPointsLog::where('user_id', $user_id)
                ->where('points', '>', 0)
                ->whereMonth('create_time')
                ->sum('points'),
            'month_consumed' => UserPointsLog::where('user_id', $user_id)
                ->where('points', '<', 0)
                ->whereMonth('create_time')
                ->sum('points'),
        ];

        return $this->success('', $stats);
    }

    /**
     * 获取系统积分统计
     */
    public function systemStats()
    {
        // 获取系统积分统计
        $stats = [
            'total_points'   => User::sum('points'),
            'total_earned'   => UserPointsLog::where('points', '>', 0)->sum('points'),
            'total_consumed' => UserPointsLog::where('points', '<', 0)->sum('points'),
            'today_earned'   => UserPointsLog::where('points', '>', 0)
                ->whereDay('create_time')
                ->sum('points'),
            'today_consumed' => UserPointsLog::where('points', '<', 0)
                ->whereDay('create_time')
                ->sum('points'),
            'month_earned'   => UserPointsLog::where('points', '>', 0)
                ->whereMonth('create_time')
                ->sum('points'),
            'month_consumed' => UserPointsLog::where('points', '<', 0)
                ->whereMonth('create_time')
                ->sum('points'),
            'user_count'     => User::where('points', '>', 0)->count(),
            'avg_points'     => User::where('points', '>', 0)->avg('points'),
        ];

        return $this->success('', $stats);
    }
}